package com.coinread.hr.tools.controller;


import com.coinread.hr.tools.bean.Info;
import com.coinread.hr.tools.bean.persistence.AdminService;
import com.coinread.hr.tools.bean.persistence.TablePersistence;
import com.coinread.hr.tools.bean.persistence.UserPersistence;
import com.coinread.hr.tools.service.MailService;
import com.coinread.hr.tools.utils.HtmlUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.mail.internet.MimeMessage;
import java.util.Calendar;
import java.util.List;

@Controller
@Slf4j
@RequestMapping("mail")
public class MailController {

    @Autowired
    private UserPersistence userPersistence;

    @Autowired
    private TablePersistence tablePersistence;

    @Autowired
    private MailService mailService;

    @Autowired
    private AdminService adminService;

    @Value("${spring.mail.username}")
    private String sender;

    @RequestMapping("send")
    public ModelAndView send(String email,String subject,String content){
        ModelAndView model = new ModelAndView("alert");
        int res = mailService.send(content,subject,email,sender,adminService.getPass());
        model.addObject("message","发送失败，请重试！");
        if (res ==1) {
            model.addObject("message", "发送成功");
        }
        return model;
    }

    @RequestMapping("check/{id}")
    public ModelAndView check(@PathVariable("id") int id){
        Info info = userPersistence.getInfo().get(id-1);
        String title = getTime()+"工资明细-"+info.getUser().getName();
        ModelAndView model = new ModelAndView("send");
        model.addObject("info",info);
        model.addObject("suject",title);
        model.addObject("content",HtmlUtils.genHtmlMailContent(info,title,tablePersistence.getTableNameList()));
        return model;
    }

    public static String getTime(){
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;
        if (month==1)
        {
            return (year-1)+"年12月";
        }
        return year+"年"+(month-1)+"月";
    }
}
